package com.cardone.platform.common.function;

import com.cardone.context.CodeException;
import com.cardone.context.function.Execution1Function;
import com.cardone.security.token.dto.TokenDto;
import com.cardone.security.token.util.TokenUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Minutes;

import java.util.Map;

/**
 * Created by c100000002 on 15-2-6.
 */
public class TokenValidateUrlFunction implements Execution1Function<TokenDto, Map<String, Object>> {
    @Getter
    @Setter
    @Accessors(chain = true)
    protected int expiresIn = 30;//默认7天:60*24*7

    @Override
    public TokenDto execution(Map<String, Object> stringObjectMap) {
        String clientId = MapUtils.getString(stringObjectMap, "client_id");
        String oldTokenKey = MapUtils.getString(stringObjectMap, "old_token_key");

        TokenDto token = TokenUtils.get(oldTokenKey);

        if (token == null) {
            throw new CodeException("失效的token");
        }

        if (!StringUtils.equals(clientId, token.getClientId())) {
            throw new CodeException("设备码不正确");
        }

        String url = MapUtils.getString(stringObjectMap, "url");

        if (!com.cardone.common.util.StringUtils.matchs(token.getUrl(), url)) {
            throw new CodeException("未授权的请求");
        }

        DateTime tokenDateTime = new DateTime(token.getCreateDate().getTime());

        DateTime nowDateTime = new DateTime();

        if (Minutes.minutesBetween(tokenDateTime, nowDateTime).getMinutes() >= expiresIn) {
            TokenUtils.remove(clientId, oldTokenKey);

            throw new CodeException("失效的token");
        }

        return token;
    }
}
